package com.sunrate.investingquote.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson2.JSON;
import com.sunrate.investingquote.bean.es.EsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.UUID;

/**
 * @author yyh
 * @description
 * @date 2023/08/21/ 15:21
 */
@RestController
@RequestMapping("/esController")
public class EsController {


    @Autowired
    private ElasticsearchClient client;


    @PostMapping("/create")
    public String test() throws IOException {
        EsUser user = new EsUser();
        user.setUsername("abcdefg");
        client.create(r -> r.index("customer").id(UUID.randomUUID().toString()).document(user));

        return "success";
    }

    @GetMapping("/testQuery")
    public void testQuery(@RequestParam(value = "name") String name, @RequestParam(value = "value") String value) throws IOException {
        SearchResponse<EsUser> search = client.search(
                req -> {
                    req.index("customer").query(
                            q -> q.term(
                                    m -> m.field(name + ".keyword").value(value)
                            )
                    );
                    return req;
                },
                EsUser.class
        );
        for (Hit<EsUser> pro : search.hits().hits()) {
            System.out.println(JSON.toJSON(pro.source()));
        }
    }
}
